<template>
  <div class="result">

    <!-- 新建、修改弹窗 -->
    <el-dialog
      width="630px"
      height="579px"
      :title="title"
      :visible.sync="createVisible"
      @close="btnCancel"
    >
      <el-form ref="createForm" label-width="120px" :model="createForm" :rules="formRules">
        <el-form-item label="型号名称 : " prop="name">
          <el-input
            style="width:396px"
            type="text"
            placeholder="请输入"
            v-model="createForm.name"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="型号编码 : " prop="model">
          <el-input
            style="width:396px"
            type="text"
            placeholder="请输入（限制数字、字母、中划线、下划线）"
            v-model="createForm.model"
            maxlength="15"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="货道行数 : " required prop="vmRow">
          <el-input-number style="width:396px" placeholder="请输入" v-model="createForm.vmRow" controls-position="right" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="货道列数 : " required prop="vmCol">
          <el-input-number style="width:396px" placeholder="请输入" v-model="createForm.vmCol" controls-position="right" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="货道容量 : " required prop="channelMaxCapacity">
          <el-input-number style="width:396px" placeholder="请输入" v-model="createForm.channelMaxCapacity" controls-position="right" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="设备图片 : " required prop="image">
          <div class="img">
            <el-upload
              accept=".jpg,.jpeg,.png,.JPG,.JPEG"
              class="avatar-uploader"
              name="fileName"
              action="https://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              >
              <!-- style="width:84px;height:84px;display:inline-block;text-align:center;line-height:84px;color:#bac0cd;border: 1px dashed #d8dde3;border-radius: 4px;background: #f3f6fb;cursor:pointer" -->
              <img style="width:100%;height:100%" v-if="createForm.image" :src="createForm.image" class="avatar">
              <i v-else class="el-icon-plus"></i>
            </el-upload>
            <div style="font-size: 14px;color: #bac0cd;">支持扩展名jpg、png文件不得大于100kb</div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-bottom:10px">
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="add"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <!-- 按钮 -->
    <el-row type="flex" class="btn">
      <el-button type="primary" class="new" @click="addDevice">
        <i class="el-icon-circle-plus-outline"></i>
        新建
      </el-button>
    </el-row>
    <!-- 表格 -->
    <el-table
       v-loading="loading"
      :header-cell-style="{
        background: '#f3f6fb',
        height: '42px',
        color: '#666',
        fontWeight: '400',
        border: 'none',
      }"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      :row-style="{ height: '44px' }"
      :cell-style="{ padding: 0, border: 'none' }"
    >
      <!-- type="index" -->
      <el-table-column prop="index" label="序号" width="80">
        <!-- <template #default="{ $index }">
          {{ $index + 1 }}
        </template> -->
      </el-table-column>
      <el-table-column prop="name" label="型号名称" width="182">
      </el-table-column>
      <el-table-column prop="model" label="型号编码" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="" label="设备图片">
        <template #default="{ row }">
          <img style="display: block;width: 24px;height: 24px;border-radius: 50%;background: #f3f6fb;border: 1px solid #f3f6fb;" :src="row.image" alt="">
        </template>
      </el-table-column>
      <el-table-column
        prop="vmRow"
        label="货道行"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="vmCol" label="货道列" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="channelMaxCapacity" label="设备容量" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="" label="操作" width="150">
        <template #default="{ row }">
          <div class="">
            <el-button type="text" @click="update(row)">修改</el-button>
            <el-button type="text" style="color:#ff5a5a" @click="delType(row.typeId)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="footer" ref="footer" v-if="paginationVisible && totalCount > pageSize">
      <span
        >共{{ this.totalCount }}条数据 第 {{ this.current }}/{{
          this.totalPage
        }}
        页</span
      >
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="pageSize"
        layout="slot"
        :total="+totalCount"
        ref="page"
      >
      <div class="btn-group">
        <el-button type="primary" ref="prev" :disabled="current === 1" :class="{ disable: current === 1 }" @click="prev">上一页</el-button>
        <el-button type="primary" ref="next" :disabled="current === +totalPage" :class="{ disable: current === +totalPage }" @click="next">下一页</el-button>
      </div>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { addSaleType, delSaleType, SaleTypeDetail, searchTypeTable, updateSaleType } from '@/api/device/device_type'
export default {
  props: {
    device: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    // 监听从搜索栏 => 父组件 => 这个组件的 device
    // 如果发生变化，就修改 tableData 的数据
    device (val) {
      if (val.length === 0) {
        this.tableData = []
        this.paginationVisible = true
      } else if (val.length === 1) {
        this.tableData = val
        // 修改索引
        val[0].index = 1
        this.paginationVisible = false
      } else {
        // code 为空的话 获取全部数据
        this.getTableData()
        this.paginationVisible = true
      }
    }
    // 监听 tableData 的变化，如果为空，则把分页隐藏
    // tableData (val) {
    //   if (!val.length) {
    //     this.$refs.footer.style.visibility = 'hidden'
    //   } else {
    //     this.$refs.footer.style.visibility = 'visible'
    //   }
    // }
  },
  created () {
    // 调用获取表格数据方法
    this.getTableData()
  },
  computed: {
    // 标题
    title () {
      return this.createForm.typeId ? '修改设备类型' : '新增设备类型'
    },
    vmStatus () {
      if (this.tableData.vmStatus === 0) {
        return '未投放'
      } else if (this.tableData.vmStatus === 1) {
        return '运营'
      } else {
        return '撤机'
      }
    }
  },
  data () {
    return {
      paginationVisible: true,
      nodeUpdate: [],
      type1: {},
      region: {},
      node1: {},
      row: {},
      updateForm: {
        nodeId: '',
        id: ''
      },
      updateVisible: false, // 修改弹窗
      loading: false, // 区域加载
      codeList: [],
      disable1: true,
      disable2: false,
      status: 0,
      // pageIndex: 1,
      pageSize: 10,
      current: 1, // 当前页
      totalCount: '', // 总条数
      totalPage: '', // 总页数
      tableData: [], // table数据
      createVisible: false, // 新增设备显示与隐藏
      type: [], // 新增时的型号
      node: [], // 新增时的点位
      createForm: {
        // 新增表单
        channelMaxCapacity: undefined, // 设备容量
        image: '', // 设备图片
        model: '', // 型号编码
        name: '', // 型号名称
        vmCol: undefined, // 货道列
        vmRow: undefined // 货道行
      },
      formRules: {
        channelMaxCapacity: [{ required: true, message: '请输入', trigger: 'blur' }],
        model: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        vmCol: [{ required: true, message: '请输入', trigger: 'blur' }],
        vmRow: [{ required: true, message: '请输入', trigger: 'blur' }],
        image: [{ required: true, message: '请上传', trigger: 'blur' }]
      }
    }
  },

  methods: {
    // 删除
    async delType (id) {
      try {
        await delSaleType(id)
        this.$message.success('删除成功')
        this.getTableData() // 重新渲染数据
      } catch (err) {
        console.log(err)
      }
    },
    // 修改确定
    async updateNode () {
      const res = await updateSaleType(this.updateForm)
      console.log(res)
      this.updateVisible = false
      this.getTableData() // 重新渲染数据
    },
    // 修改设备信息
    async update (row) {
      console.log(row)
      this.createVisible = true
      this.createForm = await SaleTypeDetail(row.typeId)
      // this.createForm = {
      //   // 新增表单
      //   channelMaxCapacity: row.channelMaxCapacity, // 设备容量
      //   image: row.image, // 设备图片
      //   model: row.model, // 型号编码
      //   name: row.name, // 型号名称
      //   vmCol: row.vmCol, // 货道列
      //   vmRow: row.vmRow // 货道行
      // }
    },
    // 新建确定
    async add () {
      try {
        await this.$refs.createForm.validate()
        if (this.createForm.typeId) {
          // 修改
          await updateSaleType(this.createForm)
        } else {
          // 新增
          await addSaleType(this.createForm) // 返回 true 或 false
        }
        // 重新渲染表格
        this.getTableData()
        // 关闭弹窗
        this.createVisible = false
      } catch (err) {
        console.log(err)
      }
    },
    // 新建取消
    btnCancel () {
      // 清空表单
      this.createForm = {
        channelMaxCapacity: undefined, // 设备容量
        image: '', // 设备图片
        model: '', // 型号编码
        name: '', // 型号名称
        vmCol: undefined, // 货道列
        vmRow: undefined // 货道行
      }
      this.$refs.createForm.resetFields()
      this.createVisible = false
    },
    // 新建
    async addDevice () {
      this.createVisible = true
    },
    // 新建表单下拉框 型号选择
    handleTypeChange () {},
    // 新建设备
    // addDevice () {},
    // 封装获取表格数据方法
    async getTableData (val) {
      this.loading = true
      const res = await searchTypeTable({
        pageIndex: this.current,
        pageSize: this.pageSize
      })
      // 将设备状态从 0 1 2 转换成 => 未投放 运营 撤机
      res.currentPageRecords.forEach((item, index) => {
        if (item.vmStatus === 0) {
          item.vmStatus = '未投放'
        } else if (item.vmStatus === 1) {
          item.vmStatus = '运营'
        } else {
          item.vmStatus = '撤机'
        }
        // 设置顺序序号
        item.index = index + 1 + res.pageSize * (res.pageIndex - 1)
      })
      // data的数据
      this.tableData = res.currentPageRecords
      // 总条数
      this.totalCount = res.totalCount
      // 总页数
      this.totalPage = res.totalPage
      this.loading = false
    },
    // 下一页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      // 处理当前页变化
      this.current = val
      // 重新获取数据
      this.getTableData()
    },
    // 按钮下一页
    next () {
      this.$refs.page.next()
      this.disable1 = false
      if (this.current >= +this.totalPage - 1) {
        // this.$refs.next.disabled = true
        this.disable2 = true
        // console.log(this.$refs.next)
      } else {
        this.disable2 = false
      }
    },
    // 按钮上一页
    prev () {
      this.$refs.page.prev()
      this.disable2 = false
      if (this.current === 1) {
        // this.$refs.next.disabled = true
        this.disable1 = true
        // console.log(this.$refs.next)
      } else {
        this.disable1 = false
      }
    },
    // 上传图片
    // async uploadHttpRequest (param) {
    //   const formData = new FormData()
    //   formData.append('file', param.file)
    //   const img = await updateImg(formData)
    //   console.log(img)
    // },
    handleAvatarSuccess (res, file) {
      // this.createForm.image = res
      console.log(res)
      this.createForm.image = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      // 获取后缀名
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 判断是否符合文件大小的限制需求
      const isLt2M = file.size / 1024 / 1024 < 0.1
      // 判断是否符合文件类型需求
      const accept = 'jpg/png'
      const isLtType = accept.indexOf(suffix) >= 0
      if (!isLtType) {
        this.$message({
          message: `上传文件格式必须为${accept}`,
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过100KB!',
          type: 'warning'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
// 新建 上传图片
.avatar-uploader {
  width:84px;height:84px;display:inline-block;text-align:center;line-height:84px;color:#bac0cd;border: 1px dashed #d8dde3;border-radius: 4px;background: #f3f6fb;cursor:pointer
}
.avatar-uploader:hover {
  border-color: #818693;
}

.result {
  padding: 20px 15px 19px 17px;
  .el-dialog__wrapper.update::v-deep {
    .el-dialog__body {
      .el-form-item {
        height: 36px;
        margin-bottom: 20px;
      }
    }
  }
  // 按钮区域
  .btn {
    margin-bottom: 20px;
    .el-button {
      width: 80px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: none;
      &.new {
        background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
      }
      &.operate {
        background-color: #fbf4f0 !important;
        color: #655b56 !important;
      }
    }
  }
  .footer {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 32px 16px;
    span {
      font-size: 16px !important;
      color: #dbdfe5 !important;
    }
    .btn-group {
      display: flex;
      .el-button {
        width: 70px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 16px;
        background-color: #d5ddf8;
        color: #606266;
        border: none;
        border-radius: 2px;
        &.disable {
          background: #edf0f9;
          color: #d8dde3;
        }
      }
    }
  }
  .el-dialog__wrapper::v-deep {
    .el-dialog {
      border-radius: 10px;
      // height: 326px;
      .el-dialog__header {
        .el-dialog__title {
          font-size: 16px;
          color: #333;
        }
      }
      .el-dialog__body {
        padding: 20px 20px 10px;
        .el-form-item {
          .el-form-item__content {
            el-cascader {
              width: 396px;
              height: 36px;
            }
          }
        }
      }
      .el-dialog__footer {
        text-align: center;
        padding: 0 20px 35px;
        .dialog-footer {
          display: flex;
          justify-content: center;
          .el-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 80px;
            height: 36px;
            border: none;
            background-color: #fbf4f0 !important;
            color: #655b56;
            &:nth-child(2) {
              margin-left: 34px;
              background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
              color: #fff;
            }
          }
        }
      }
    }
  }
}
</style>
